package com.wzh.glsc.cart.config;

import com.wzh.common.constant.AuthServerConstant;
import com.wzh.common.constant.CartConstant;
import com.wzh.common.vo.MemberVo;
import com.wzh.glsc.cart.to.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author xiaoming
 * @PackageName:com.wzh.glsc.cart.config
 * @ClassName:@{NAME}
 * @Description: 执行方法前 拦截请求 判断用户的登录状态
 * @date:@{DATE}@{TIME}
 */
//拦截器必须实现 HandlerInterceptor 接口
//@Component // 这里不能直接放在容器中，要注册拦截器到mvc中
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> toThreadLocal=new ThreadLocal<>();

    /**
     *  目标方法执行之前
     * @param request
     * @param response
     * @param handler
     * @return return true放行   return false 不放行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //TODO 为什么这里报错后进入了多次？
        UserInfoTo userInfoTo=new UserInfoTo();
        HttpSession session=request.getSession();
        MemberVo loginUser =new MemberVo();
        if(session.getAttribute(AuthServerConstant.LOGIN_USEER)!=null){
            loginUser = (MemberVo) session.getAttribute(AuthServerConstant.LOGIN_USEER);
        }
        if(StringUtils.isNotEmpty(loginUser.getNickname())){
            //已登录
            //如果登录就放入userId到 userInfoTo中
            userInfoTo.setUserId(loginUser.getId());
        }
        //不管是否登录都要取出临时的数据
        Cookie[] cookie=request.getCookies();
        //这里要进行非空判断，否则在没有cookie时在第一次进入这时会报错
        if(cookie!=null){
            for (Cookie c : cookie) {
                //这里比对的是声明的常量值：用户临时key user-key
                if(c.getName().equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                    //如果将未登录时的数据userKey放入到userInfoTo中
                    userInfoTo.setUserKey(c.getValue());
                    break;
                }
            }
        }

        //如果没有临时用户则一定分配一个临时用户
        if(StringUtils.isEmpty(userInfoTo.getUserKey())){
            userInfoTo.setUserKey(UUID.randomUUID().toString());
        }
        //放入共享线程中
        toThreadLocal.set(userInfoTo);
        return true;
    }

    /**
     *  业务执行之后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //给临时用户续期并放入cookie中
        Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, toThreadLocal.get().getUserKey());
        //扩大作用域
        cookie.setDomain("gulimall.com");
        //设置过期时间
        cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
        response.addCookie(cookie);
    }
}
